package cn.groupmarket.trigger.http;

import cn.groupmarket.api.IMarketTradeService;
import cn.groupmarket.api.dto.LockMarketPayOrderRequestDTO;
import cn.groupmarket.api.dto.LockMarketPayOrderResponseDTO;
import cn.groupmarket.api.response.Response;
import cn.groupmarket.domain.activity.model.entity.MarketProductEntity;
import cn.groupmarket.domain.activity.model.entity.TrialBalanceEntity;
import cn.groupmarket.domain.activity.model.valobj.GroupBuyActivityDiscountVO;
import cn.groupmarket.domain.activity.service.IIndexGroupBuyMarketService;
import cn.groupmarket.domain.trade.model.entity.MarketPayOrderEntity;
import cn.groupmarket.domain.trade.model.entity.PayActivityEntity;
import cn.groupmarket.domain.trade.model.entity.PayDiscountEntity;
import cn.groupmarket.domain.trade.model.entity.UserEntity;
import cn.groupmarket.domain.trade.model.valobj.GroupBuyProgressVO;
import cn.groupmarket.domain.trade.service.ITradeOrderService;
import cn.groupmarket.types.enums.ResponseCode;
import cn.groupmarket.types.exception.AppException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;

@Slf4j
@RestController()
@CrossOrigin("*")
@RequestMapping("/api/v1/gbm/trade/")
public class TradeOrderController implements IMarketTradeService {
    @Resource
    private ITradeOrderService tradeOrderService;
    @Resource
    private IIndexGroupBuyMarketService indexGroupBuyMarketService;

    @Override
    @RequestMapping(value = "lock_payorder",method = RequestMethod.POST)
    public Response<LockMarketPayOrderResponseDTO> lockMarketPayOrder(@RequestBody LockMarketPayOrderRequestDTO lockMarketPayOrderRequestDTO) {
        try{
            String userId = lockMarketPayOrderRequestDTO.getUserId();
            String source = lockMarketPayOrderRequestDTO.getSource();
            String channel = lockMarketPayOrderRequestDTO.getChannel();
            String goodsId = lockMarketPayOrderRequestDTO.getGoodsId();
            Long activityId = lockMarketPayOrderRequestDTO.getActivityId();
            String outTradeNo = lockMarketPayOrderRequestDTO.getOutTradeNo();
            String teamId = lockMarketPayOrderRequestDTO.getTeamId();

            log.info("营销交易锁单:{} LockMarketPayOrderRequestDTO:{}", userId, JSON.toJSONString(lockMarketPayOrderRequestDTO));

            if(StringUtils.isBlank(userId) || StringUtils.isBlank(source) || StringUtils.isBlank(channel) || StringUtils.isBlank(goodsId)){
                return  Response.<LockMarketPayOrderResponseDTO>builder()
                        .code(ResponseCode.ILLEGAL_PARAMETER.getCode())
                        .info(ResponseCode.ILLEGAL_PARAMETER.getInfo())
                        .build();
            }

            MarketPayOrderEntity marketPayOrderEntity = tradeOrderService.queryNoPayMarketPayOrderByOutTradeNo(outTradeNo, userId);
            if(marketPayOrderEntity != null){
                LockMarketPayOrderResponseDTO lockMarketPayOrderResponseDTO = LockMarketPayOrderResponseDTO.builder()
                        .orderId(marketPayOrderEntity.getOrderId())
                        .deductionPrice(marketPayOrderEntity.getDeductionPrice())
                        .tradeOrderStatus(marketPayOrderEntity.getTradeOrderStatusEnumVO().getCode())
                        .build();
                log.info("交易锁单记录（存在）:{} marketPayOrderEntity {}", userId,JSON.toJSONString(lockMarketPayOrderResponseDTO));
                return Response.<LockMarketPayOrderResponseDTO>builder()
                        .code(ResponseCode.SUCCESS.getCode())
                        .info(ResponseCode.SUCCESS.getInfo())
                        .data(lockMarketPayOrderResponseDTO)
                        .build();
            }

            if(null != teamId){
                GroupBuyProgressVO groupBuyProgressVO = tradeOrderService.queryGroupBuyProgress(teamId);
                if(groupBuyProgressVO != null && Objects.equals(groupBuyProgressVO.getTargetCount(),groupBuyProgressVO.getLockCount())){
                    return Response.<LockMarketPayOrderResponseDTO>builder()
                            .code(ResponseCode.E0006.getCode())
                            .info(ResponseCode.E0006.getInfo())
                            .build();
                }
            }

            TrialBalanceEntity trialBalanceEntity = indexGroupBuyMarketService.indexMarketTrial(MarketProductEntity.builder()
                            .userId(userId)
                            .source(source)
                            .channel(channel)
                            .productId(goodsId)
                            .activityId(activityId)
                            .build());
            GroupBuyActivityDiscountVO groupBuyActivityDiscountVO = trialBalanceEntity.getGroupBuyActivityDiscountVO();

            marketPayOrderEntity = tradeOrderService.lockMarketPayOrder(UserEntity.builder().userId(userId).build(),
                    PayDiscountEntity.builder()
                            .source(source)
                            .channel(channel)
                            .goodsId(goodsId)
                            .goodsName(trialBalanceEntity.getProductName())
                            .originalPrice(trialBalanceEntity.getOriginalPrice())
                            .deductionPrice(trialBalanceEntity.getDeductionPrice())
                            .payPrice(trialBalanceEntity.getPayPrice())
                            .outTradeNo(outTradeNo)
                            .build(),
                    PayActivityEntity.builder()
                            .activityId(activityId)
                            .activityName(groupBuyActivityDiscountVO.getActivityName())
                            .teamId(teamId)
                            .targetCount(groupBuyActivityDiscountVO.getTarget())
                            .endTime(groupBuyActivityDiscountVO.getEndTime())
                            .startTime(groupBuyActivityDiscountVO.getStartTime())
                            .build());

            return Response.<LockMarketPayOrderResponseDTO>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(LockMarketPayOrderResponseDTO.builder()
                            .orderId(marketPayOrderEntity.getOrderId())
                            .deductionPrice(marketPayOrderEntity.getDeductionPrice())
                            .tradeOrderStatus(marketPayOrderEntity.getTradeOrderStatusEnumVO().getCode())
                            .build())
                    .build();

        }catch (AppException e){
            return Response.<LockMarketPayOrderResponseDTO>builder()
                    .code(e.getCode())
                    .info(e.getInfo())
                    .build();
        }catch (Exception e){
            return Response.<LockMarketPayOrderResponseDTO>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .build();
        }
    }
}
